# """
# 示例路由，展示不同的认证使用方式
# """

from datetime import datetime, timedelta
from typing import Optional
from fastapi import APIRouter, HTTPException, status, Depends, Request
from fastapi.security import HTTPAuthorizationCredentials

from app.core.auth import (
    get_current_user_optional,
    get_current_user_required,
    get_current_superuser,
    auth_required,
    auth_optional,
    security
)
from app.schemas.base.login import CredentialsSchema, JWTOut, JWTPayload
from app.utils.user import verify_password, create_access_token_with_expiry, get_password_hash
from app.core.config import settings
from app.utils.request import RequestHandler

router = APIRouter(prefix="/auth", tags=["认证示例"])


# 模拟用户数据库
FAKE_USERS_DB = {
    "admin": {
        "user_id": 1,
        "username": "admin",
        "hashed_password": get_password_hash("123456"),
        "is_superuser": True
    },
    "user": {
        "user_id": 2,
        "username": "user",
        "hashed_password": get_password_hash("123456"),
        "is_superuser": False
    }
}


@router.post("/login", summary="用户登录")
async def login(credentials: CredentialsSchema):
    """
    用户登录接口
    不需要认证，在白名单中
    """
    user = FAKE_USERS_DB.get(credentials.username)
    
    if not user or not verify_password(credentials.password, user["hashed_password"]):
        return RequestHandler.unauthorized(
            message="用户名或密码错误",
            remarks="请检查您的登录凭证"
        )
    
    # 创建JWT payload
    jwt_payload = {
        "user_id": user["user_id"],
        "username": user["username"],
        "is_superuser": user["is_superuser"],
    }
    
    # 创建token
    token = create_access_token_with_expiry(data=jwt_payload)
    
    return RequestHandler.success(
        data={
            "access_token": token,
            "token_type": "bearer",
            "username": user["username"],
            "expires_in": settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES * 60
        },
        message="登录成功",
        remarks=f"欢迎回来，{user['username']}!"
    )

##   带认证的接口写法  。。测试尝试写  
# ## Depends 是 FastAPI 提供的一个函数/类，用于声明依赖关系：
# ## dependency 指的是实际的依赖函数或组件，也就是 Depends() 中传入的那个函数：
#  示例1：使用依赖注入的可选认证
@router.get("/profile/optional", summary="可选认证的用户资料")
async def get_profile_optional(
    current_user: Optional[JWTPayload] = Depends(get_current_user_optional)
):
    """
    可选认证的接口
    如果提供了有效token，返回用户信息；否则返回访客信息
    """
    if current_user:
        return RequestHandler.success(
            data={
                "user_id": current_user.user_id,
                "username": current_user.username,
                "is_superuser": current_user.is_superuser,
                "access_time": datetime.now().isoformat()
            },
            message=f"欢迎，{current_user.username}！",
            remarks="已认证用户访问"
        )
    else:
        return RequestHandler.success(
            data={
                "user_id": None,
                "username": "访客",
                "is_authenticated": False,
                "access_time": datetime.now().isoformat()
            },
            message="欢迎，访客！",
            remarks="未认证用户访问"
        )


# 示例2：使用依赖注入的必需认证
@router.get("/profile/required", summary="必需认证的用户资料")
async def get_profile_required(
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """
    必需认证的接口
    必须提供有效token才能访问
    """
    return RequestHandler.success(
        data={
            "user_id": current_user.user_id,
            "username": current_user.username,
            "is_superuser": current_user.is_superuser,
            "access_time": datetime.now().isoformat(),
            "token_valid": True
        },
        message=f"你好，{current_user.username}！",
        remarks="正在访问受保护的用户资料"
    )


# 示例3：超级用户专用接口
@router.get("/admin/users", summary="管理员专用：获取用户列表")
async def get_users_admin(
    current_user: JWTPayload = Depends(get_current_superuser)
):
    """
    超级用户专用接口
    只有超级用户才能访问
    """
    users_list = [
        {
            "user_id": user_data["user_id"],
            "username": user_data["username"],
            "is_superuser": user_data["is_superuser"]
        }
        for user_data in FAKE_USERS_DB.values()
    ]
    
    return RequestHandler.success(
        data={
            "users": users_list,
            "total_count": len(users_list),
            "admin_user": current_user.username
        },
        message="用户列表获取成功",
        remarks=f"管理员 {current_user.username} 正在查看系统用户"
    )


# 示例4：使用装饰器的强制认证
@router.get("/secure/data", summary="装饰器强制认证")
@auth_required
async def get_secure_data(request: Request, current_user: JWTPayload = None):
    """
    使用装饰器强制认证的接口
    即使全局禁用认证，此接口仍需要认证
    """
    return RequestHandler.success(
        data={
            "sensitive_data": "这是机密数据",
            "user_info": {
                "user_id": current_user.user_id,
                "username": current_user.username,
                "is_superuser": current_user.is_superuser
            },
            "access_time": datetime.now().isoformat(),
            "security_level": "high"
        },
        message="安全数据获取成功",
        remarks="此接口使用@auth_required装饰器，强制要求认证"
    )


# 示例5：使用装饰器的可选认证
@router.get("/public/info", summary="装饰器可选认证")
@auth_optional
async def get_public_info(request: Request, current_user: Optional[JWTPayload] = None):
    """
    使用装饰器可选认证的接口
    可以访问，但如果提供了token会显示用户信息
    """
    if current_user:
        return RequestHandler.success(
            data={
                "public_content": "这是公开信息",
                "visitor_info": {
                    "type": "authenticated_user",
                    "user_id": current_user.user_id,
                    "username": current_user.username,
                    "is_superuser": current_user.is_superuser
                },
                "access_time": datetime.now().isoformat()
            },
            message="公开信息获取成功",
            remarks=f"已认证用户 {current_user.username} 正在访问"
        )
    else:
        return RequestHandler.success(
            data={
                "public_content": "这是公开信息",
                "visitor_info": {
                    "type": "anonymous",
                    "user_id": None,
                    "username": "匿名访客"
                },
                "access_time": datetime.now().isoformat()
            },
            message="公开信息获取成功",
            remarks="匿名访客正在访问"
        )


# 示例6：系统状态接口（不需要认证）
@router.get("/status", summary="系统状态")
async def get_auth_status():
    """
    系统认证状态接口
    显示当前认证配置状态
    """
    return RequestHandler.success(
        data={
            "auth_config": {
                "auth_enabled": settings.enable_auth,
                "auth_whitelist": settings.auth_whitelist,
                "jwt_expire_minutes": settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES
            },
            "system_info": {
                "debug_mode": settings.debug,
                "cors_origins": settings.cors_origins
            }
        },
        message="系统状态获取成功",
        remarks="认证系统配置信息"
    )


# 示例7：刷新token接口
@router.post("/refresh", summary="刷新Token")
async def refresh_token(
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """
    刷新token接口
    使用当前有效token获取新的token
    """
    # 创建新的JWT payload
    jwt_payload = {
        "user_id": current_user.user_id,
        "username": current_user.username,
        "is_superuser": current_user.is_superuser,
    }
    
    # 创建新token
    new_token = create_access_token_with_expiry(data=jwt_payload)
    
    return RequestHandler.success(
        data={
            "access_token": new_token,
            "token_type": "bearer",
            "expires_in": settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES * 60,
            "username": current_user.username,
            "refresh_time": datetime.now().isoformat()
        },
        message="Token刷新成功",
        remarks=f"用户 {current_user.username} 的token已更新"
    )